/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/convert-binary-search-tree-to-doubly-linked-list
   @Language: C++
   @Datetime: 19-04-01 17:30
   */

/**
 * Definition of Doubly-ListNode
 * class DoublyListNode {
 * public:
 *     int val;
 *     DoublyListNode *next, *prev;
 *     DoublyListNode(int val) {
 *         this->val = val;
 *         this->prev = this->next = NULL;
 *     }
 * } * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	void inorder(TreeNode *root, DoublyListNode **head, DoublyListNode **prev){
		if(root==NULL) return;
		inorder(root->left,head,prev);
		DoublyListNode *node=new DoublyListNode(root->val);
		if(*prev){
			node->prev=*prev;
			(*prev)->next=node;
		}
		else *head=node;
		*prev=node;
		inorder(root->right,head,prev);
	}
public:
	/**
	 * @param root: The root of tree
	 * @return: the head of doubly list node
	 */
	DoublyListNode * bstToDoublyList(TreeNode * root) {
		// write your code here
		DoublyListNode *head=NULL,*prev=NULL;
		inorder(root,&head,&prev);
		return head;
	}
};
